var express = require("express");
var router = express.Router();
var { Menu, Role, User, Roles,Organization, schedule,Roles,Classes } = require('../models/model');
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});
/* GET home page. */
//获取当前时间

router.get("/", function(req, res, next) {
  res.render("index", { title: "Express" });
});

router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username, password }).populate('role')
  if (user) {
    res.send({
      code: 200,
      msg: '登录成功',
      data: user
    })
  } else {
    res.send({
      code: 400,
      msg: '用户名或密码错误',
    })
  }
})

router.get('/getTable', async (req, res) => {
  let { searchName, searchType } = req.query;
  console.log(searchName, searchType);
  let regName = new RegExp(searchName)
  let list = []
  if (regName) {list.push({scheduleName:regName})}
  if (searchType) {list.push({scheduleType:searchType})}
  if (list.length > 0) {
    let data = await schedule.find({ $and: list })
    res.send({
      code: 200,
      msg: '获取成功',
      data: data
    })
  } else {
    let data = await schedule.find()
    res.send({
      code: 200,
      msg: '获取成功',
      data: data
    })
  }
})

router.post('/addSchedule', async (req, res) => {
  let data = req.body
  console.log(data);
  //将数据添加到第一位
  await schedule.create(data)
  res.send({
    code: 200,
    msg: '日程添加成功',
  })
})

router.post('/upSchedule',async(req,res)=>{
  let data = req.body
  console.log(data);
  await schedule.updateOne({_id:data._id},data)
  res.send({
    code: 200,
    msg: '日程修改成功',
  })
})

router.post('/addManyExcel',async(req,res)=>{
  let list = req.body
  console.log(list);
  await schedule.insertMany(list)
  res.send({
    msg:'文件导入成功',
    code:200
  })
})



router.get('/getMenu', async (req, res) => {
  let { id } = req.query;

  const [{ menus }] = await Role.find({ _id: id }).lean()
  const menu = await Menu.find().lean()
  let data = []
  menus.forEach((item) => {
    menu.forEach((item1) => {
      if (String(item1._id) == String(item)) {
        data.push(item1)
      }
    })


  })
  let list = []
  let obj = {}
  data.forEach((item) => {
    obj[item._id] = item
  })

  data.forEach((item) => {
    if (!item['pid']) {
      list.push(item)
    } else {
      if (obj[item['pid']] && !obj[item['pid']]['children']) {
        obj[item['pid']]['children'] = []
      }
      if (obj[item['pid']]) {
        obj[item['pid']]['children'].push(item)
      }
    }
  })
  res.send({
    code: 200,
    msg: '获取成功',
    data: list
  })

})

// 添加机构

router.post('/addOrganization',async(req,res)=>{
  const { name, type, pid, desc, status, employees } = req.body;
  const data = await Organization.create({ name, type, pid, desc, status, employees })
  res.send({
    code:200,
    msg:'添加成功',
    data:data
  })
})

router.get('/getTreeOrganization',async(req,res)=>{
  let company = await Organization.find({type:'分公司'})
  let data = await Organization.find().lean()
  let list = []
  let obj = {}
  data.forEach((item) => {
    obj[item['_id']] = item
  })

  data.forEach((item) => {
    if (!item.pid) {
      list.push(item)
    } else {
      if (obj[item['pid']] && !obj[item['pid']]['children']) {
        obj[item['pid']]['children'] = []
      }
      if (obj[item['pid']]) {
        obj[item['pid']]['children'].push(item)
      }
    }
  })

  res.send({
    code: 200,
    msg: '获取成功',
    data: list,
    company:company
  })
  // console.log(list);
})

router.get('/getOrganization',async(req,res)=>{
  let list = await Organization.find()

    res.send({
      code:200,
      msg:'获取成功',
      data:list
    })

  await Organization.deleteMany({ pid: req.body._id })

  await Roles.deleteMany({ oid: req.body._id })

})
// 删除机构部门
router.post('/deleteDepartment', async (req, res) => {
  await Organization.deleteOne({ _id: req.body._id })

  await Roles.deleteMany({ oid: req.body._id })

})


// 修改机构
router.post('/updateOrganization', async (req, res) => {
  const { _id, addname, type, pid, desc, status, employees } = req.body;
  await Organization.updateOne({ _id }, { name:addname, type, pid, desc, status, employees })
  res.send({
    code: 200,
  })
})



//获取部门及岗位
router.get('/getOgrRole',async(req,res)=>{
  let data = await Organization.aggregate([
    {
      $lookup: {
        from: 'Roles',
        localField: '_id',
        foreignField: 'oid',
        as: 'roles'
      }
    }
  ])
  res.send({
    data
  })
}
)

// 获取岗位
router.get('/getRolelist',async(req,res)=>{
  let data = await Roles.find()
  res.send({
    data
  })
})

//添加人员

router.post('/addUser', async (req, res) => {
  const { username, card, status, desc, rid, roles,phone,type,oid,partid } = req.body;
  const data = await User.create({ username, card, role:roles, status, desc, rid, phone,type, oid, partid })
  res.send({
    code: 200,
  })
  // console.log(type)
})


// 获取人员

router.get('/getuserrole',async(req,res)=>{
  let data = await User.find().populate(['rid', 'oid', "partid"])
  // console.log(data)
  res.send({
    data
  })
})

// 删除人员

router.post('/deleteuser', async (req, res) => {
  const { _id } = req.body;
  await User.deleteOne({ _id })
  // console.log(_id)
  res.send({
    code: 200,
  })
})

// 修改人员

router.post('/updateuser', async (req, res) => {
  const { _id, username, card, status, desc, rid, roles, phone, type, oid, partid } = req.body;
  
  await User.updateOne({ _id }, { username, card, role: roles, status, desc, rid, phone, type, oid, partid })
  
  res.send({
    code: 200,
  })
})

router.post('/changeuserstatus', async (req, res) => {
  await User.updateOne({ _id: req.body._id }, { status: req.body.status })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})
router.get('/deleteSchedule', async (req, res) => {
  let { id } = req.query;
  await schedule.deleteOne({ _id: id })
  res.send({
    code: 200,
    msg: '删除成功',
  })
})
router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username, password }).populate("role");
  if (user) {
    res.send({
      code: 200,
      msg: "登录成功",
      data: user
    });
  } else {
    res.send({
      code: 400,
      msg: "用户名或密码错误"
    });
  }
});

router.get("/getMenu", async (req, res) => {
  let { id } = req.query;
  // const [{menus}] = await Role.find({_id:id}).lean()
  const [{ menus }] = await Role.find({ _id: id }).lean();
  const menu = await Menu.find().lean();
  let data = [];
  menus.forEach(item => {
    menu.forEach(item1 => {
      if (String(item1._id) == String(item)) {
        data.push(item1);
      }
    });
  });
  // const data = await Menu.find()
  let list = [];
  let obj = {};
  data.forEach(item => {
    obj[item._id] = item;
  });

  data.forEach(item => {
    if (!item["pid"]) {
      list.push(item);
    } else {
      if (obj[item["pid"]] && !obj[item["pid"]]["children"]) {
        obj[item["pid"]]["children"] = [];
      }
      if (obj[item["pid"]]) {
        obj[item["pid"]]["children"].push(item);
      }
    }
  });

  res.send({
    code: 200,
    msg: "获取成功",
    data: list
  });
});
//添加排班日历
router.post("/addClass", async (req, res) => {
  let {
    year,
    month,
    day,
    classesName,
    startTime,
    endTime,
    user,
    isAbsent,
    isLeave
  } = req.body;
  Classes.insertMany({
    year,
    month,
    day,
    classesName,
    startTime,
    endTime,
    user,
    isAbsent,
    isLeave
  });
  res.send({
    code: 200,
    msg: "添加成功"
  });
});
//获取排班日历
router.get("/getClasses", async (req, res) => {
  let { id } = req.query;
  let data = await Classes.find({ user: id });
  res.send({
    code: 200,
    msg: "获取成功",
    data
  });
});
//上班打卡
router.post("/work", async (req, res) => {
  let { id, year, month, day } = req.body;
  const list = [];
  list.push({ user: id }, { year }, { month }, { day });
  let data = await Classes.findOne({ $and: list });
  let time = new Date();
  let workmonth = time.getMonth() + 1;
  let workday = time.getDate();
  let hour = time.getHours();
  let minute = time.getMinutes();
  data.workTime = month + "月" + day + "日" + hour + "时" + minute + "分";
  data.isAbsent = false;
  data.isLeave = false;
  await Classes.updateOne({ _id: data._id }, data);
  res.send({
    code: 200,
    msg: "上班打卡成功"
  });
});

//获取雇员信息
router.get("/getEmployee", async (req, res) => {
  let data = await Classes.aggregate([
    {
      $lookup: {
        from: "users",
        localField: "user",
        foreignField: "_id",
        as: "userInfo"
      }
    }
  ]);
  let list = [];
  console.log(data);
  res.send({
    code: 200,
    msg: "获取成功",
    data
  });
});
router.get("/ljt_getOrganization",async(req,res)=>{
  let data = await Organization.find()
  res.send({
    code:200,
    msg:'获取成功',
    data:data
  })
})


router.get("/ljt_getRoles",async(req,res)=>{
  const {name, oid} = req.query;
  let roles = []
  if(name != '' && oid != '请选择部门'){
    let text = new RegExp(name)
    roles = await Roles.find({$and:[{name:text},{oid}]}).populate("oid")
  }else if(name != ''){
    console.log(name);
    let text = new RegExp(name)
    roles = await Roles.find({name:text}).populate("oid")
  }else if(oid != '请选择部门'){
    roles = await Roles.find({oid}).populate("oid")
  }else{
    roles = await Roles.find().populate("oid")
  }
  res.send({
    code:200,
    msg:'获取成功',
    roles
  })
})


router.post("/ljt_addRole", (req,res)=>{
  const data = req.body;
  Roles.create(data)
  res.send({
    code:200,
    msg:'添加成功'
  })
})


router.delete("/ljt_delRole",async(req,res)=>{
  const {id} = req.query;
  await Roles.findByIdAndDelete(id)
  res.send({
    code:200,
    msg:'删除成功'
  })
})


router.post("/ljt_updateRole",async(req,res)=>{
  const {id, obj} = req.body
  await Roles.findByIdAndUpdate(id, obj)
  res.send({
    code:200,
    msg:'修改成功'
  })
})


router.post("/ljt_updateRoleStatus",async(req,res)=>{
  const {id,status} = req.body;
  await Roles.findByIdAndUpdate(id,{status})
  res.send({
    code:200,
    msg:'修改成功'
  })
})

module.exports = router;
